<?php

namespace paymch\components;

use Yii;
use yii\filters\VerbFilter;
use yii\helpers\Inflector;
use common\models\trade\Trade;
use paymch\models\BusinessNotify;

class Controller extends \yii\web\Controller {

    /**
     * 禁用当前控制器CSRF校验
     * @internal
     */
    public $enableCsrfValidation = false;

    /**
     * @var false|interge 交易ID
     */
    private $_tradeid = false;

    /**
     * 当前绑定请求方式POST
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    '*' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 获取当前交易
     */
    public function getTrade() {
        if ($this->_tradeid) {
            return Trade::findOne($this->_tradeid);
        }
        return null;
    }

    /**
     * 设置当前交易ID
     */
    public function setTradeId($tradeid) {
        $this->_tradeid = $tradeid;
    }

    /**
     * 执行异步处理动作
     * @return mixed
     */
    public function afterAction($action, $result) {
        if ($this->trade != null) {
            $this->updateTrade();
        }
        //记录日志-保存动作执行结果
        static::log('after-' . $action->id, $result);

        return parent::afterAction($action, $result);
    }

    /**
     * 异步订单处理
     * @return mixed
     */
    protected function updateTrade() {
        $trade = $this->trade;
        if ($trade->status == Trade::STATUS_WAITPAY) {
            $pay = $trade->getOrders()->sum('pay*status*balance');
            $btotal = $trade->total * $trade->balance;
            $total = strval($btotal);

            if ($pay == 0) {
                $trade->status = Trade::STATUS_CLOSED;
            } elseif ($total == $pay) {
                $trade->status = Trade::STATUS_SUCCESS;
            } else {
                $_print = [
                    'PAY' => $pay,
                    'Total' => $btotal,
                    'Total strval' => $total,
                ];
                Yii::error('修改状态时金额不一致：' . print_r($_print, true));
            }
        }
        $trade->save();
        if ($trade->status == Trade::STATUS_SUCCESS) {
            //通知业务订单成功了
            $notify = new BusinessNotify($trade->id);
            $status = $notify->save($msg);
            //记录日志
            static::log('BusinessNotify', [
                'trade_id' => $trade->id,
                'status' => $status,
                'msg' => $msg,
            ]);
        }
    }

    /**
     * 记录日志
     */
    public static function log($prefix, $content) {
        Yii::error([
            'method' => __METHOD__,
            'prefix' => Inflector::id2camel($prefix),
            'result' => $content,
        ], 'payment');
    }

}
